package com.purang.web.schedule.quartz.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.purang.web.mapper.TableOperationMapper;
import com.purang.web.schedule.quartz.core.QuartzRegister;
import com.purang.web.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

/**
 * 数据库表定时任务
 *
 * @author Zheming Liu
 * @version 1.0-RELEASE
 * @since 1.0-RELEASE
 */
@Slf4j
@QuartzRegister(jobDetailName = "table", cronExpression = "*/5 * * * * ?")
public class TableScheduleJob extends QuartzJob {

    @Autowired
    private TableOperationMapper tableOperationMapper;

    @Override
    void doJob(JobExecutionContext jobExecutionContext) {
        List<String> tables = tableOperationMapper.showTables();
        HashMap<String, String> params = new HashMap<>();
        params.put("sp_no", "100001");
        JSONObject queryTablesResult = HttpClientUtils
                .builder()
                .xForm(params)
                .uri("/info/meta/querytable.htm")
                .build()
                .executeHttp();
        JSONArray tableJsonArray = queryTablesResult.getJSONArray("data");
        for (int i = 0; i < tableJsonArray.size(); i++) {
            JSONObject tableJson = tableJsonArray.getJSONObject(i);
            String tableNo = tableJson.getString("tableNo");
            if (!tables.contains(tableNo)) {
                params.put("tableNo", tableNo);
                JSONObject queryTableFieldResult = HttpClientUtils
                        .builder()
                        .xForm(params)
                        .uriFromMap("query-field")
                        .build()
                        .executeHttp();
                log.info("The query table result are {}", queryTableFieldResult);
            }
        }
        log.info("The project tables are {}", tables);
        log.info("The query table result are {}", queryTablesResult);
    }
}
